package com.yw.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.yw.codeManageInfo.domain.CodeManageInfo;
import com.yw.codeManageInfo.dto.AddCodeDTO;
import com.yw.codeManageInfo.dto.QueryDTO;
import com.yw.dataStandardCatalog.domain.DataStandardCatalog;
import com.yw.piliangDTO.StatusDTO;
import com.yw.result.PageDTO;
import com.yw.result.R;
import com.yw.service.CodeManageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;


@Slf4j
@RestController
@Tag(name = "码表管理",description = "码表管理")
@RequestMapping("/codeManage")
public class CodeManageController {
    @Resource
    private CodeManageService codeManageService;

    @Operation(summary = "条件分页查询所有码表",description = "条件分页查询所有码表")
    @PostMapping("/pageAllByQuery")
    public R pageAllByQuery(@RequestBody QueryDTO queryDTO){
        return  R.OK(codeManageService.pageAllByQuery(queryDTO));
    }

    @Operation(summary = "根据码表id查询码值表",description = "根据码表id查询码值表")
    @PostMapping("/getConfigurationByCodeId/{id}")
    public R getConfigurationByCodeId(@PathVariable Integer id){
        return  R.OK(codeManageService.getConfigurationByCodeId(id));
    }

    @Operation(summary = "删除一条数据",description = "删除一条数据")
    @PostMapping("/deleteCode")
    public R deleteCode(Integer id){
        return codeManageService.removeById(id)?R.OK():R.FAIL();
    }

    @Operation(summary = "添加一条数据",description = "添加一条数据")
    @PostMapping("/addCode")
    public R addCode(@RequestBody AddCodeDTO addCodeDTO){
        return codeManageService.addCode(addCodeDTO)?R.OK():R.FAIL();
    }

    @Operation(summary = "编辑码表",description = "编辑码表")
    @PostMapping("/updateCode/{id}")
    public R updateCode(@PathVariable Integer id, @RequestBody AddCodeDTO addCodeDTO){
        return codeManageService.updateCode(id,addCodeDTO)?R.OK("修改成功"):R.FAIL("修改失败");
    }

    @Operation(summary = "更改码表状态",description = "更改码表状态")
    @PostMapping("/updateStatic/{id}")
    public R updateStatic(@PathVariable Integer id){
        return codeManageService.updateStatic(id)?R.OK():R.FAIL();
    }

    @PostMapping(value = "/insertFile",consumes = "multipart/form-data")
    public R uploadExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.FAIL("文件为空");
        }
        try {
            // 调用读取Excel的方法
            List<CodeManageInfo> data = readExcel(file);
            // 打印或处理读取的数据
            System.out.println(data);
            return R.OK("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return R.FAIL("文件上传失败"+ e.getMessage());
        }
    }

    //    批量发布停用
    @Operation(summary = "批量发布停用")
    @PostMapping("/batch")
    public R batch(@RequestBody StatusDTO statusDTO){
        return codeManageService.batch(statusDTO)?R.OK("批量发布成功"):R.FAIL("批量发布失败");
    }


    @Operation(summary = "码表下载")
    @PostMapping ("/download")
    public ResponseEntity<byte[]> downloadExcel() {
        byte[] fileContent = codeManageService.exportDataToExcel();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "data.xlsx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileContent);
    }

    @Operation(summary = "数据资产新增时得到码表名")
    @PostMapping ("/codeNames")
    public R codeNames(){
       return R.OK(codeManageService.codeNames());
    }


    private List<CodeManageInfo> readExcel(MultipartFile file) throws IOException {
        return EasyExcel.read(file.getInputStream(), DataStandardCatalog.class, new ReadListener<CodeManageInfo>() {
            @Override
            public void invoke(CodeManageInfo data, AnalysisContext context) {
                System.out.println("读取到的数据：" + data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                System.out.println("所有数据读取完成！");
            }
        }).sheet().doReadSync();
    }
}
